/**
 * 
 */
package dms.repository.impl;



import org.hibernate.Session;
import org.hibernate.Transaction;

import dms.model.role.Account;
import dms.repository.AccountRepository;
import dms.util.HibernateUtil;

/**
 * @author 李健
 *
 */
public class AccountRepositoryHibernate implements AccountRepository {

	public AccountRepositoryHibernate() {}
	
	@Override
	public void changePassword(String name, String newPassword) {
		Session session = null;
		Transaction tx = null;
		
		Account account = null;
		String queryString = "update Account a set a.password = :password where a.name = :name";
		try {
			session = HibernateUtil.getSessionFactory().getCurrentSession();
			tx = session.beginTransaction();
			
			session.createQuery(queryString)
			 	   .setParameter("password", newPassword)
			 	   .setParameter("name", name)
			 	   .executeUpdate();			
			
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			if (tx != null) {
				tx.rollback();
			}
		} finally {
			if (session != null) {
				if (session.isOpen()) {
					session.close();
				}
			}
		}
		
	}

	@Override
	public Account findAccountById(long id) {
		Session session = null;
		Transaction tx = null;
		
		Account account = null;
		
		try {
			session = HibernateUtil.getSessionFactory().getCurrentSession();
			tx = session.beginTransaction();
			
			account = (Account) session.load(Account.class, id);
			
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			if (tx != null) {
				tx.rollback();
			}
		} finally {
			if (session != null) {
				if (session.isOpen()) {
					session.close();
				}
			}
		}
		
		return account;
	}

	@Override
	public Account findAccountByName(String name) {
		Session session = null;
		Transaction tx = null;
		
		Account account = null;
		String queryString = "select a from Account a where a.name = :name ";
		
		try {
			session = HibernateUtil.getSessionFactory().getCurrentSession();
			tx = session.beginTransaction();
			
			account = (Account) session.createQuery(queryString)
				   .setParameter("name", name)
				   .uniqueResult();
			
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			if (tx != null) {
				tx.rollback();
			}
		} finally {
			if (session != null) {
				if (session.isOpen()) {
					session.close();
				}
			}
		}
		return account;
	}

}
